package moltencore.network.serverlobby.strategy;

import moltencore.network.protocol.Login;
import moltencore.network.protocol.LoginResponse;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.network.protocol.Base;
import spark.utility.IncrementalLongIdFactory;
import moltencore.player.PlayerList;
import moltencore.player.Player;
import moltencore.player.exception.PlayerNameAlreadyExistsException;
import moltencore.player.exception.PlayerAlreadyRegisteredException;
import org.apache.log4j.Logger;
import spark.utility.OutWrapper;

import java.util.Collection;

public class LoginStrategy implements IProtocolHandleStrategy<Login> {
	private Logger logger = Logger.getLogger(LoginStrategy.class);
	private PlayerList<Player> playerList;
	private IncrementalLongIdFactory clientIdFactory = new IncrementalLongIdFactory();

	public LoginStrategy(PlayerList<Player> playerList) {
		this.playerList = playerList;
	}

	@Override
	public void handle(Login packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		LoginResponse response = new LoginResponse(packet);

		String playerName = packet.getName();
		try {
			playerList.login(new Player(playerName, packet.getSession(), clientIdFactory.getNextId()));
			response.setAccepted(true);
		}
		catch(PlayerNameAlreadyExistsException e) {
			logger.info("Multiple login of player " + playerName + " attempted");
			response.setAccepted(false);
			response.setMessage("A player named " + playerName + " is already online");
		}
		catch(PlayerAlreadyRegisteredException e) {
			logger.info("Multiple login of player with session " + packet.getSession() + " attempted");
			response.setAccepted(false);
			response.setMessage("Your session " + packet.getSession() + " is already in use.");
		}

		acknowledgement.value = response;
	}
}
